package oc_mysql

import (
	"fmt"
	"log"
	"oc_saas/internal/glo"
	"oc_saas/internal/model/base"
	"os"

	mysqlServer "gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 总体的orm
func OrmMysql() *gorm.DB {
	m := glo.OC_CONF.Mysql
	if m.DbName == "" {
		return nil
	}
	mysqlConfig := mysqlServer.Config{
		DSN:                       m.Dsn(), // DSN data source name
		DefaultStringSize:         191,     // string 类型字段的默认长度
		SkipInitializeWithVersion: false,   // 根据版本自动配置
	}
	if db, err := gorm.Open(mysqlServer.New(mysqlConfig), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   glo.OC_CONF.Server.Prefix + "_", //全局表明前缀
			SingularTable: glo.OC_CONF.Mysql.Singular,
		},
	}); err != nil {
		log.Fatal(err)
		panic(err)
		return nil
	} else {
		fmt.Println("mysql初始化成功", m.Dsn())
		db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(m.MaxIdleConn)
		sqlDB.SetMaxOpenConns(m.MaxOpenConn)
		return db
	}
}

// 初始化租户分库连接
func AllDbConnect(db *gorm.DB) (allDbs map[string]*gorm.DB) {
	var db_list []*base.TenancyDB
	err := db.Model(&base.TenancyDB{}).Find(&db_list).Error
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if len(db_list) == 0 {
		return
	}
	var dbInitList = make(map[string]*gorm.DB)
	for _, v := range db_list {
		mysqlConfig := mysqlServer.Config{
			DSN:                       fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true&loc=Local", v.Username, v.Password, v.Domain, v.DbName),
			DefaultStringSize:         191,
			SkipInitializeWithVersion: false,
		}
		if db, err := gorm.Open(mysqlServer.New(mysqlConfig), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
			NamingStrategy: schema.NamingStrategy{
				TablePrefix:   glo.OC_CONF.Server.TenancyPrefix + "_",
				SingularTable: true,
			},
		}); err != nil {
			log.Fatal(err)
		} else {
			db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
			sqlDB, _ := db.DB()
			sqlDB.SetMaxIdleConns(v.MaxIdleConns)
			sqlDB.SetMaxOpenConns(v.MaxOpenConns)
			dbInitList[v.Domain+"/"+v.DbName] = db
		}
	}
	return dbInitList
}
